//
//  VCCreateAccount.swift
//  AirlineReservation
//
//  Created by Kevin on 2019/12/27.
//  Copyright © 2019 Kevin. All rights reserved.
//

import UIKit

class VCCreateAccount: VCBase {
    
    // 注册账号View
    lazy var createAccountView: ViewBaseInput = {
        let ui = ViewBaseInput()
        ui.isShowBtn = true
        ui.titleLabel = "注册账号"
        ui.backgroundColor = UIColor.white
        ui.nameArrs = [USERNAME,PASSWORD,PASSWORD_AGAIN,EMAIL,GENDER,MOBILE,IDNUMBER]
        ui.createViews()
        let uiY = realHeight + MARGIN10
        ui.frame = CGRect(x: 0, y: uiY, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - uiY)
        return ui
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加控件
        init_views()
        // 事件监听
        init_event()
    }
}

// MARK: 逻辑部分
extension VCCreateAccount {
    
    func createAccount(user:UserInfo) -> Void {
        // 校验数据是否有效
        if user.username?.count == 0 {
            self.show(text: "用户名不能为空")
            return
        }
        if user.password?.count == 0 {
            self.show(text: "密码不能为空")
            return
        }
        if user.passwordAgain?.count == 0 {
            self.show(text: "确认密码不能为空")
            return
        }
        if !user.password!.elementsEqual(user.passwordAgain!) {
            self.show(text: "密码不一致")
            return
        }
        if user.email?.count == 0 {
            self.show(text: "邮箱不能为空")
            return
        }
        if user.mobile?.count == 0 {
            self.show(text: "手机号不能为空")
            return
        }
        if user.idnumber?.count == 0 {
            self.show(text: "身份证号不能为空")
            return
        }
        // 拼接数据
        let dict = NSMutableDictionary()
        dict.setValue(user.email, forKey: SP_EMAIL)
        dict.setValue(user.mobile, forKey: SP_MOBILE)
        dict.setValue(user.gender, forKey: SP_GENDER)
        dict.setValue(user.idnumber, forKey: SP_IDNUMBER)
        dict.setValue(user.username, forKey: SP_USERNAME)
        dict.setValue(user.password, forKey: SP_PASSWORD)
        // 请求
        self.doPost(api: "reg/account", dict: dict) { (dict) in
            self.show(text: "注册成功")
            // 解析数据
            let result = dict.value(forKey: SP_BODYREQUEST) as! NSDictionary
            // 存数据
            UserDefaults.standard.setValue(result.value(forKey: SP_USERID), forKey: SP_USERID)
            self.navigationController?.popViewController(animated: true)
        }
    }
}

// MARK: 初始化
extension VCCreateAccount {
    
    func init_event() -> Void {
        createAccountView.complete = { user in
            self.createAccount(user: user)
        }
    }
    
    func init_views() -> Void {
        view.addSubview(backroundWhite)
        view.addSubview(createAccountView)
    }
}
